package com.wnzt.baszh.quartz;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

import org.apache.axis.client.Call;
import org.apache.cxf.jaxws.context.WebServiceContextImpl;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.wnzt.baszh.entity.MedicalFile;
import com.wnzt.baszh.entity.MedicalPdf;
import com.wnzt.baszh.service.IArchivingService;
import com.wnzt.baszh.util.common.GlobalFun;
import com.wnzt.baszh.util.common.SetSystemProperty;
import com.wnzt.baszh.util.common.WebServiceUtil;

/**
 * 电子病历系统的接口方案-后台自动归档
 * @author [lv tang wei]
 * [2017年5月19日]
 */
@Component
@DisallowConcurrentExecution
public class AutoFileJob {
	
	@Autowired
	private IArchivingService archivingService;
	
	static int searchIndexFlag = 0;
	
	@Async
	public void execute() {
		if (searchIndexFlag > 0)
			return ;
		searchIndexFlag = 1;// 锁定
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    	Map<String,String> map=SetSystemProperty.propertiesToMap(path+"/config.properties");
		String execDate = map.get("exec.date");
		String now = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
		String strDirPath = getRequest().getSession().getServletContext().getRealPath("/");
		if (execDate == null || !now.equals(execDate)) {
			System.out.println("自动归档时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			SetSystemProperty.updateProperties("exec.date", new SimpleDateFormat("yyyyMMddHHmm").format(new Date()));
			map = SetSystemProperty.propertiesToMap(path + "/config.properties");
			try {
	    		WebServiceUtil util=new WebServiceUtil();
				Call call = util.getMedicalCall();// 获取medical WebServer连接
				//第一步，查询系统未归档数据
				
				List<Map<String,Object>> list=archivingService.getNotArchived();
				if(list.size()>0){
					//第二步，调用电子病历接口，获取病人的全部电子病历列表
					for (Map<String, Object> data : list) {
						//第三部，获取指定电子病历的PDF文件
						String inParamXml=util.getMedicalFilelistParamStr(data);//入参转换为xml格式
						//获取全部电子病历
						String outParamXml = (String) call.invoke(new Object[] { inParamXml }); // 获取返回结果
						//解析全部电子病历返回
						List<MedicalFile> medicalFileList = util.parserMedicalFilelistResultXml(outParamXml);
						for (MedicalFile mf : medicalFileList) {
							if(!GlobalFun.hasValue(mf.getFpdfpath())){//没有pdf才去接口获取pdf文件
								//有需要获取的pdf才连接
								data.put("medicalids", mf.getMedicalid());
								call = util.getMedicalPdfCall();// 获取pdf WebServer连接
								inParamXml=util.getMedicalPdfParamStr(data);//入参转换为xml格式
								outParamXml = (String) call.invoke(new Object[] { inParamXml }); //获取返回结果
								List<MedicalPdf> medicalPdfs = util.parserMedicalPdfResultXml(outParamXml);
								for (MedicalPdf mp : medicalPdfs) {
									if(GlobalFun.hasValue(mp.getFpath())||null!=mp.getFilebyte()){//电子病历PDF文件流，fpath和filebyte其中一个必须非空
										//将归档信息保存至数据库
										this.archivingService.addArchived(data.get("FPRN")+"", data.get("FTIMES")+"","1");
										//有病历id才保存
										//执行将pdf文件上传至服务器
										InputStream fis = new ByteArrayInputStream(mp.getFilebyte());
										//本地路径\病案号\住院次数\病历类型\
										String filepath=strDirPath+map.get("archive.pdf.path")+data.get("FPRN")+"\\"+data.get("FTIMES");
										util.CreateMultilayerFile(filepath);//创建多级目录
										File file =new File(filepath);    
										//如果文件夹不存在则创建    
										if  (!file .exists()  && !file .isDirectory()){       
										    file .mkdir();    
										}
										file=new File(filepath+"\\"+mf.getFtitle()+".pdf");    
										if(!file.exists()){    
										    try {    
										        file.createNewFile();    
										    } catch (IOException e) {    
										        e.printStackTrace();    
										    }    
										}
										FileOutputStream os = new FileOutputStream(file);   //文件的输出流文件的路径为fileto 
									    byte[] buffer = new byte[1024];   //定义缓存的字节数组为1K 
									    int len = fis.read(buffer);       //将文件读入字节数组 
									    while (len != -1) { 
									    	os.write(buffer,0,len);       //将文件写到指定的路径下 
									    	len = fis.read(buffer); 
										} 
										fis.close(); 
										os.close(); 
									}
								}
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println(e.getMessage());
			} 
		}
		searchIndexFlag=0;
	}
	
	/**
	 * 取request
	 * @author [lv tang wei]
	 * Describe:
	 * @return
	 * [2017年7月5日]
	 */
	public HttpServletRequest getRequest(){
		WebServiceContext context = new WebServiceContextImpl();
		MessageContext ctx = context.getMessageContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(AbstractHTTPDestination.HTTP_REQUEST);
		return request;
	}
}
